﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Visitor;
using Taste;

namespace ASTClass
{
    class ReadAST : OperatorAST
    {
        public ReadAST() :base() { name = "Read";  }
        public ReadAST(AST parent) : base(parent) { name = "Read"; }

        public override AST Clone()
        {
            ReadAST ast = new ReadAST();
            ast.operators = operators;
            foreach (AST c in children)
                ast.children.Add(c.Clone());

            return ast;
        }

        #region Visitor pattern

        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion Visitor pattern

        public override void CodeGen(Taste.SymbolTable symTab, Taste.CodeFileGen cfg)
        {
            if (ChildCount() > 0)
            {
                IdentAST readvar = children[0] as IdentAST;
                Var myvar = symTab.findLocalVar(readvar.Value);
                cfg.AddCommand("li", "$v0, 5");
                cfg.AddCommand("syscall", null);

                if (myvar != null)
                {
                    //local
                    cfg.AddCommand("sw", "$v0, " + 4 * myvar.index + "($fp)");
                }
                else
                {
                    myvar = symTab.findGlobalVar(readvar.Value);
                    if (myvar != null)
                    {
                        //global
                        IdentAST id1 = myvar.variable as IdentAST;
                        cfg.AddCommand("sw", "$v0, " + id1.Value + "($0)");
                    }
                    else
                    {
                        //error
                        Console.WriteLine("Error, variable " + readvar.Value + " not found!");
                        throw new Exception();
                    }
                }
            }
        }
    }
}
